const express = require('express');
const router = express.Router();
const pool = require('../db');

// 游戏查询接口
router.get('/search', async (req, res) => {
  try {
    const { id, title, page = 1 } = req.query;
    const pageSize = 6;
    const offset = (page - 1) * pageSize;
    
    let query;
    let params;
    
    // 优先使用id查询
    if (id) {
      query = 'SELECT title, cover_image, wangpan_link FROM games WHERE id = ? LIMIT ? OFFSET ?';
      params = [id, pageSize, offset];
    } else if (title) {
      query = 'SELECT title, cover_image, wangpan_link FROM games WHERE title LIKE ? LIMIT ? OFFSET ?';
      params = [`%${title}%`, pageSize, offset];
    } else {
      // 如果没有查询条件，返回所有数据
      query = 'SELECT title, cover_image, wangpan_link FROM games LIMIT ? OFFSET ?';
      params = [pageSize, offset];
    }

    // 获取总数的查询
    let countQuery;
    let countParams;
    
    if (id) {
      countQuery = 'SELECT COUNT(*) as total FROM games WHERE id = ?';
      countParams = [id];
    } else if (title) {
      countQuery = 'SELECT COUNT(*) as total FROM games WHERE title LIKE ?';
      countParams = [`%${title}%`];
    } else {
      countQuery = 'SELECT COUNT(*) as total FROM games';
      countParams = [];
    }

    // 执行查询
    pool.query(query, params, (error, results) => {
      if (error) {
        console.error('查询游戏列表失败:', error);
        return res.status(500).json({
          code: 500,
          success: false,
          msg: '查询失败',
          data: null
        });
      }

      // 查询总数
      pool.query(countQuery, countParams, (countError, countResults) => {
        if (countError) {
          console.error('查询总数失败:', countError);
          return res.status(500).json({
            code: 500,
            success: false,
            msg: '查询失败',
            data: null
          });
        }

        const total = countResults[0].total;
        const totalPages = Math.ceil(total / pageSize);

        res.json({
          code: 200,
          success: true,
          msg: '查询成功',
          data: {
            list: results,
            pagination: {
              current: parseInt(page),
              pageSize,
              total,
              totalPages
            }
          }
        });
      });
    });
  } catch (error) {
    console.error('接口异常:', error);
    res.status(500).json({
      code: 500,
      success: false,
      msg: '服务器内部错误',
      data: null
    });
  }
});

module.exports = router;